#include "user.h"

#define DEV_WRITE 0XA0
#define DEV_READ  0XA1
void at24c02_init()
{
    iic_init();
}

uint8_t at24c02_write_data(uint8_t *data,uint8_t size,uint8_t begin)
{
    iic_start();
    iic_send_data(DEV_WRITE);
    if(iic_get_ack())
    {
        iic_end();
        return 0;
    }
    iic_send_data(begin);
    if(iic_get_ack())
    {
        iic_end();
        return 0;
    }
    uint8_t sendBytes=0;
    while(sendBytes<size)
    {

        uint8_t page_off=begin%8;
        uint8_t page_left=8-page_off;
        if(page_left>size-sendBytes)
            page_left=size-sendBytes;
        for(int i=0; i<page_left; i++)
        {
            iic_send_data(data[sendBytes++]);
            if(iic_get_ack())
            {
                iic_end();
                return sendBytes;
            }
        }
		delay_hs(40);
        begin+=page_left;
        if(sendBytes<size)
        {
            iic_end();
			delay_hs(10);
            iic_start();
            iic_send_data(DEV_WRITE);
            if(iic_get_ack())
            {
                iic_end();
                return 0;
            }
            iic_send_data(begin);
            if(iic_get_ack())
            {
                iic_end();
                return 0;
            }
        }
    }
	iic_end();
	return sendBytes;
}

uint8_t at24c02_read_data(uint8_t *data,uint8_t size,uint8_t begin)
{
	iic_start();
    iic_send_data(DEV_WRITE);
    if(iic_get_ack())
    {
        iic_end();
        return 0;
    }
    iic_send_data(begin);
    if(iic_get_ack())
    {
        iic_end();
        return 0;
    }
	iic_start();
    iic_send_data(DEV_READ);
    if(iic_get_ack())
    {
        iic_end();
        return 0;
    }
	int bytes;
	for(bytes=0;bytes<size;bytes++)
	{
		if(bytes!=size-1)
		{
			data[bytes]=iic_rec_data();
			iic_send_ack(0);
		}
		else
		{
			data[bytes]=iic_rec_data();
			iic_send_ack(1);
		}
	}
	iic_end();
	return bytes;
}
